<template>
  <div class="">

  </div>
  
</template>

<script>
export default {
  data(){
    return{
      db: null,
      request: null
    }
  },
  created(){
    this.loadData()
  },
  methods:{
    loadData(){
      let _this = this
      // 创建数据库
      var request = window.indexedDB.open('myDB');      
      // 创建表——没有库的时候触发
      request.onupgradeneeded = function(event) {          
        _this.db = event.target.result;
        var objectStore;
        if (!_this.db.objectStoreNames.contains('person')) {
          objectStore = _this.db.createObjectStore('person', { keyPath: 'id' });
          objectStore.createIndex('name', 'name', { unique: false });
          objectStore.createIndex('email', 'email', { unique: true });
        }
      }
      
      request.onerror = function (event) {
        console.log('数据库打开报错');
      };
      request.onsuccess = function (event) {
        _this.db = request.result;
        console.log('数据库打开成功');
        setTimeout(() => {
          _this.add()
        }, 0);
      };
    },
    add() {
      let _this = this
      var request = _this.db.transaction(['person'], 'readwrite')
        .objectStore('person')
        .add({
          id: 1, name: '张三1', age: 24, email: 'zhangsan@example.com',
        });
      request.onsuccess = function (event) {
        console.log('数据写入成功');
      };
      request.onerror = function (event) {
        console.log('数据写入失败');
      }
    }
  }
}
</script>

<style>


</style>